package com.frejoys.common.exception;

import cn.hutool.core.util.StrUtil;
import com.frejoys.common.config.ValueConfig;
import com.frejoys.common.error.HttpStatus;
import com.frejoys.common.request.ThreadContext;
import com.frejoys.common.response.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.MessageSource;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.reactive.function.client.WebClientResponseException;


/**
 * 统一异常处理
 */
@Slf4j
@RestControllerAdvice
@RequiredArgsConstructor
public class CommonExceptionHandler {

    // 国际化
    private final MessageSource messageSource;

    private final ValueConfig valueConfig;


    // @ExceptionHandler(GeneralException.class)
    // public Result handleCommonException(GeneralException e) {
    //     return Result.fail(e.getCode(), e.getMessage(), null);
    // }

    @ExceptionHandler(Exception.class)
    public Result handleCommonException(Exception e) {
        // e.printStackTrace();
        if (valueConfig.getActiveProfiles().equals("dev,dao-dev")) {
            e.printStackTrace();
        }
        log.error("全局异常：", e);

        // 自定义异常
        if (e instanceof GeneralException ge) {
            String msg = messageSource.getMessage(ge.getCode().toString(), null, ThreadContext.get().getLocale());
            return Result.fail(ge.getCode(), StrUtil.isEmpty(msg) ? "" : msg, null);
        }

        if (e instanceof MethodArgumentNotValidException) {
            return Result.fail(HttpStatus.argumentNotValid, ((MethodArgumentNotValidException) e).getBindingResult().getFieldError().getDefaultMessage());
        }

        if (e instanceof HttpRequestMethodNotSupportedException) {
            return Result.fail(HttpStatus.reqMethod);
        }

        if (e instanceof WebClientResponseException) {
            return Result.fail(HttpStatus.reqClientFailure);
        }

        if (e instanceof HttpMessageNotReadableException) {
            return Result.fail(HttpStatus.reqClientFailure);
        }

        if (e instanceof HttpMediaTypeNotAcceptableException) {
            return Result.fail(HttpStatus.routeMediaTypeFail);
        }

        return Result.fail(HttpStatus.systemError);
    }

}
